import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth'
import NProgress from 'nprogress'

// 基础路由
const constantRoutes = [
  {
    path: '/auth',
    component: () => import('@/layouts/AuthLayout.vue'),
    children: [
      {
        path: 'login',
        name: 'Login',
        component: () => import('@/views/auth/Login.vue'),
        meta: { title: '登录', requiresAuth: false }
      },
      {
        path: 'register',
        name: 'Register',
        component: () => import('@/views/auth/Register.vue'),
        meta: { title: '注册', requiresAuth: false }
      }
    ]
  },
  {
    path: '/error',
    name: 'Error',
    children: [
      {
        path: '403',
        name: 'Error403',
        component: () => import('@/views/error/403.vue'),
        meta: { title: '403', requiresAuth: false }
      },
      {
        path: '404',
        name: 'Error404',
        component: () => import('@/views/error/404.vue'),
        meta: { title: '404', requiresAuth: false }
      }
    ]
  }
]

// 动态路由
const asyncRoutes = [
  {
    path: '/',
    component: () => import('@/layouts/DefaultLayout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Index.vue'),
        meta: { title: '工作台', requiresAuth: true, icon: 'dashboard' }
      },
      {
        path: 'system',
        name: 'System',
        redirect: '/system/user',
        meta: { title: '系统管理', requiresAuth: true, icon: 'system' },
        children: [
          {
            path: 'user',
            name: 'SystemUser',
            component: () => import('@/views/system/user/Index.vue'),
            meta: { title: '用户管理', requiresAuth: true, icon: 'user' }
          },
          {
            path: 'role',
            name: 'SystemRole',
            component: () => import('@/views/system/role/Index.vue'),
            meta: { title: '角色管理', requiresAuth: true, icon: 'role' }
          },
          {
            path: 'permission',
            name: 'SystemPermission',
            component: () => import('@/views/system/permission/Index.vue'),
            meta: { title: '权限管理', requiresAuth: true, icon: 'permission' }
          },
          {
            path: 'menu',
            name: 'SystemMenu',
            component: () => import('@/views/system/menu/Index.vue'),
            meta: { title: '菜单管理', requiresAuth: true, icon: 'menu' }
          }
        ]
      },
      {
        path: 'monitor',
        name: 'Monitor',
        redirect: '/monitor/log',
        meta: { title: '系统监控', requiresAuth: true, icon: 'monitor' },
        children: [
          {
            path: 'log',
            name: 'MonitorLog',
            component: () => import('@/views/monitor/log/Index.vue'),
            meta: { title: '操作日志', requiresAuth: true, icon: 'document' }
          }
        ]
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/profile/Index.vue'),
        meta: { title: '个人信息', requiresAuth: true, icon: 'user', hidden: true }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/error/404'
  }
]

const routes = [...constantRoutes, ...asyncRoutes]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  const authStore = useAuthStore()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - RBAC权限管理系统`
  }
  
  // 白名单路径
  const whiteList = ['/auth/login', '/auth/register', '/error/403', '/error/404']
  
  if (authStore.isLoggedIn) {
    // 已登录用户
    if (to.path === '/auth/login') {
      next('/')
      return
    }
    
    // 确保用户信息和菜单已加载
    if (!authStore.userInfo) {
      try {
        await authStore.getCurrentUser()
      } catch (error) {
        console.error('获取用户信息失败:', error)
        authStore.logout()
        next('/auth/login')
        return
      }
    }
    
    // 确保菜单已加载
    if (authStore.menus.length === 0) {
      try {
        await authStore.loadUserMenus()
      } catch (error) {
        console.error('加载菜单失败:', error)
      }
    }
    
    next()
  } else {
    // 未登录用户
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/auth/login')
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router